package com.wenli.lt.java8;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

public class streamTest {
    /*steam  filter 过滤*/
    /**
     * filter 方法用于通过设置的条件过滤出元素
     */
    @Test
    public void filterStream(){
        List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
//        List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
        List<String> filterStr = strings.stream().filter(string -> !StringUtils.isBlank(string)).collect(Collectors.toList());
        filterStr.stream().forEach(System.out::println);
        long count = strings.stream().filter(string -> string.isEmpty()).count();
        System.out.println(count);
    }
/**
 * steam  map
 * map 方法用于映射每个元素到对应的结果
 */
    /**
     * limit 方法用于获取指定数量的流。
     */
@Test
public void mapStream(){
    List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
    // 获取对应的平方数
    //distinct() 去重
//    List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());
    List<Integer> squaresList = numbers.stream().map( i -> i*i > 9 ? i*i : 11).distinct().limit(2).collect(Collectors.toList());
    squaresList.stream().forEach(System.out::println);
}

/**
 * sorted
 * sorted 方法用于对流进行排序
 */
    @Test
    public void  sortedStream(){
        List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
        List<Integer> squaresList = numbers.stream().map( i -> i*i > 9 ? i*i : 11).distinct().sorted().collect(Collectors.toList());
        squaresList.stream().forEach(System.out::println);
    }

    /**
 * Collectors 类实现了很多归约操作 例如将流转换成集合和聚合元素 Collectors 可用于返回列表或字符串：
 */
    @Test
    public void CollectorsSteam(){
        List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
        List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
        System.out.println("筛选列表: " + filtered);
        String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", "));
        System.out.println("合并字符串: " + mergedString);
    }

    /**
     * parallelStream 是流并行处理程序的代替方法。以下实例我们使用 parallelStream 来输出空字符串的数量
     */
    @Test
    public void parallelStream(){
            List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
            // 获取空字符串的数量
        long count = strings.parallelStream().filter(string -> string.isEmpty()).count();
        System.out.println(count);
    }

}
